package com.chenss.dragonser.activity;

import android.app.Activity;
import android.app.Dialog;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.support.v4.util.ArrayMap;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.ashokvarma.bottomnavigation.BottomNavigationBar;
import com.ashokvarma.bottomnavigation.BottomNavigationItem;
import com.ashokvarma.bottomnavigation.TextBadgeItem;
import com.chenss.dragonser.R;
import com.chenss.dragonser.app.AppInfo;
import com.chenss.dragonser.app.Constant;
import com.chenss.dragonser.base.BaseActivity;
import com.chenss.dragonser.fragment.GoodsFragment;
import com.chenss.dragonser.fragment.OrderFragment;
import com.chenss.dragonser.fragment.ServiceFragment;
import com.chenss.dragonser.model.GoodsListModel;
import com.chenss.dragonser.model.VersionModel;
import com.chenss.dragonser.network.NetworkRequest;
import com.chenss.dragonser.network.RequestCallbcak;
import com.chenss.dragonser.response.GoodsListResponse;
import com.chenss.dragonser.utils.GsonUtil;
import com.chenss.dragonser.utils.ToastUtil;

import org.json.JSONException;

import java.util.List;

public class MainActivity extends BaseActivity implements RequestCallbcak {
    private TextView tv_order;
    private TextView tv_service;
    private TextView tv_goods;
    private FrameLayout ly_content;

    private OrderFragment f1;
    private GoodsFragment f2;
    private ServiceFragment f3;
    private FragmentManager fragmentManager;

    public NetworkRequest networkRequest;//网络请求
    public ArrayMap<String, String> parmMap;//请求参数封装

    @Override
    public void initParms(Bundle parms) {

    }

    @Override
    public int bindLayout() {
        return R.layout.activity_main;
    }

    @Override
    public void initView(View view) {
        tv_order = findView(R.id.tv_order);
        tv_goods = findView(R.id.tv_goods);
        tv_service = findView(R.id.tv_service);
        ly_content = findView(R.id.ly_content);

        tv_order.setOnClickListener(this);
        tv_service.setOnClickListener(this);
        tv_goods.setOnClickListener(this);

        tv_order.performClick();
    }

    /**
     * 版本更新
     */
    private void getVersionInfo() {
        parmMap = new ArrayMap<>();
        Constant.setCommonParams(parmMap, Constant.App.Advert, Constant.classes.Advert_an_UpdateVersionServe);
        networkRequest.postJsonRequest(Constant.serverPath, parmMap, Constant.Actionid.NETWORK_REQUEST_CODE_1, false, Constant.classes.Advert_an_UpdateVersionServe);
    }

    //重置所有文本的选中状态
    public void selected() {
        tv_order.setSelected(false);
        tv_service.setSelected(false);
        tv_goods.setSelected(false);
    }

    //隐藏所有Fragment
    public void hideAllFragment(FragmentTransaction transaction) {
        if (f1 != null) {
            transaction.hide(f1);
        }
        if (f2 != null) {
            transaction.hide(f2);
        }
        if (f3 != null) {
            transaction.hide(f3);
        }

    }

    @Override
    public void doBusiness(Context mContext) {
        networkRequest = new NetworkRequest(mContext, this);
        getVersionInfo();
    }

    @Override
    public void widgetClick(View v) {
        FragmentTransaction transaction = getFragmentManager().beginTransaction();
        hideAllFragment(transaction);
        switch (v.getId()) {
            case R.id.tv_order:
                selected();
                tv_order.setSelected(true);
                if (f1 == null) {
                    f1 = new OrderFragment();
                    transaction.add(R.id.ly_content, f1);
                } else {
                    transaction.show(f1);
                }
                break;
            case R.id.tv_goods:
                selected();
                tv_goods.setSelected(true);
                if (f2 == null) {
                    f2 = new GoodsFragment();
                    transaction.add(R.id.ly_content, f2);
                } else {
                    transaction.show(f2);
                }
                break;
            case R.id.tv_service:
                selected();
                tv_service.setSelected(true);
                if (f3 == null) {
                    f3 = new ServiceFragment();
                    transaction.add(R.id.ly_content, f3);
                } else {
                    transaction.show(f3);
                }
                break;


        }

        transaction.commit();
    }

    @Override
    public void onFaild(int orderCode, String result) {
        ToastUtil.showShort(this, result);
    }

    @Override
    public void onSucceed(int orderCode, String result) throws JSONException {
        if (orderCode == Constant.Actionid.NETWORK_REQUEST_CODE_1) {
            Log.e("-------------", result);
            VersionModel versionModel = GsonUtil.GsonToBean(result, VersionModel.class);
            if (null != versionModel) {

                if (0 == versionModel.getStatus()) {

                    if (!getVersion().equals(versionModel.getData().getVersion_num())) {
                        final String version_url = versionModel.getData().getVersion_url();
                        if (TextUtils.isEmpty(version_url))
                            return;
                        showDownloadDialog(version_url);
                    }else {
                        ToastUtil.showShort(this , "当前已是最新版本");

                    }
                } else {

                    ToastUtil.showShort(this , versionModel.getMsg());
                }

            }


        }
    }

    /**
     * 获取VersionCode
     *
     * @return 当前应用的版本号
     */
    public static int getVersionCode(Context context)// 获取版本号(内部识别号)
    {
        try {
            PackageInfo pi = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), 0);
            return pi.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return 0;
        }
    }


    /**
     * 获取版本号
     *
     * @return 当前应用的版本号
     */
    public String getVersion() {
        try {
            PackageManager manager = this.getPackageManager();
            PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
            String version = info.versionName;
            return version;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    private void showDownloadDialog(final String version_url) {
        final Dialog dialog = new Dialog(this, R.style.DialogStyle);
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(true);
        View view = LayoutInflater.from(this).inflate(R.layout.item_dialogphone, null);
        dialog.setContentView(view);
        TextView tv_title = (TextView) view.findViewById(R.id.tv_title);
        TextView tvSexCancel = (TextView) view.findViewById(R.id.tvSexCancel);
        TextView tvPhone = (TextView) view.findViewById(R.id.tvPhone);
        TextView tvSexSend = (TextView) view.findViewById(R.id.tvSexSend);
        tv_title.setText("有新版本更新");
        tvPhone.setText("当前有新版本，点击去下载");
        tvSexSend.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setAction("android.intent.action.VIEW");
                Uri content_url = Uri.parse(version_url);
                intent.setData(content_url);
                startActivity(intent);
                dialog.dismiss();
            }
        });
        tvSexCancel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        Window mWindow = dialog.getWindow();
        WindowManager.LayoutParams lp = mWindow.getAttributes();
        lp.width = getScreenWidth(this);
        mWindow.setGravity(Gravity.CENTER);
//        mWindow.setWindowAnimations(R.style.dialogAnim);
        mWindow.setAttributes(lp);
        dialog.show();
    }

    public int getScreenWidth(Context context){
        DisplayMetrics dm = new DisplayMetrics();
        ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(dm);
        return dm.widthPixels;
    }
}
